<?php
require($_SERVER['DOCUMENT_ROOT'].'/setting.php');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 0, 'message' => 'Only POST requests are allowed']);
    exit;
}
if (!isset($_POST['token'])) {
    echo json_encode(['status' => 0, 'message' => 'Token is missing']);
    exit;
}
if(!isset($_POST['tokens'])){
    echo json_encode(['status' => 0, 'message' => 'Token is missing']);
    exit;
}
$correct_token = 'yhalpomxhys0183';
if ($_POST['token'] !== $correct_token) {
    echo json_encode(['status' => 0, 'message' => 'Invalid token']);
    exit;
}
if($_POST['tokens'] !== $website_array['quascode']){
    echo json_encode(['status' => 0, 'message' => 'Invalid token']);
    exit;
}
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['status' => 0, 'message' => 'No file uploaded or upload error']);
    exit;
}
if (!class_exists('ZipArchive')) {
    echo json_encode(['status' => 0, 'message' => 'ZipArchive class is not available']);
    exit;
}
$target_dir = $_SERVER['DOCUMENT_ROOT'] . '/cofd/authorization/';
if (!is_dir($target_dir)) {
    if (!mkdir($target_dir, 0755, true)) {
        echo json_encode(['status' => 0, 'message' => 'Failed to create target directory']);
        exit;
    }
}
if (!is_dir($target_dir)) {
    if (!mkdir($target_dir, 0755, true)) {
        echo json_encode(['status' => 0, 'message' => 'Failed to create target directory']);
        exit;
    }
}
if ($handle = opendir($target_dir)) {
    while (($item = readdir($handle)) !== false) {
        if ($item !== '.' && $item !== '..') {
            if (is_file($target_dir . $item)) {
                if (!unlink($target_dir . $item)) {
                    echo json_encode(['status' => 0, 'message' => 'Failed to delete existing files']);
                    exit;
                }
            }
        }
    }
    closedir($handle);
}
$zip = new ZipArchive();
if ($zip->open($_FILES['file']['tmp_name']) !== true) {
    echo json_encode(['status' => 0, 'message' => 'Failed to open zip file']);
    exit;
}
if (!$zip->extractTo($target_dir)) {
    echo json_encode(['status' => 0, 'message' => 'Failed to extract zip file']);
    exit;
}
$zip->close();
if (!unlink($_FILES['file']['tmp_name'])) {
    echo json_encode(['status' => 0, 'message' => 'Failed to delete zip file']);
    exit;
}
echo json_encode(['status' => 1, 'message' => 'File uploaded and extracted successfully']);